import {Log} from "../../util/Log";
import {_} from "../../util/UtilTs";


export interface VSequelize{
    [x: string]: any;
}

export class EasyAORM<Sequelize extends VSequelize>{
    sq:Sequelize = null;
    SequelizeClass = null;
    private getModelsFunc;

    constructor(SequelizeClass,getModelsFunc,dbInfo,configs){
        this.SequelizeClass = SequelizeClass;
        this.sq = new SequelizeClass(dbInfo.name, dbInfo.user, dbInfo.pass, configs);
        this.getModelsFunc = getModelsFunc;
    }

    async start(){
        const self:any = this;
        try{
            await this.sq.authenticate();
            Log.info(`数据库连接成功:${JSON.stringify(this.sq.config,null,4)}`);
        }catch(err){
            Log.err(`数据库连接失败:${JSON.stringify(this.sq.config,null,4)}`);
            console.log(err);
            process.exit();
        }

        //自动填充model
        const models = this.getModelsFunc(this.sq);

        _.each(self,(val,key)=>{
            if(val === 'mm'){
                self[key] = models[key];
            }
        });

    }

    query=async (sql) => await this.sq.query(sql,{ type: this.SequelizeClass.QueryTypes.SELECT});


    //分页
    public async page(selectFields,sql,pageSize,pageNumber){
        const SequelizeClass = this.SequelizeClass;

        const page = {
            rows:0, //总的记录
            pageSize:pageSize, //每页的记录数
            pageNumber:pageNumber, //当前页数
            firstPage : false, //是否是第一也
            lastPage : false, //是否是最后一页
            totalPage : 0, //总的页面
            list:[]
        };

        //先取总数
        page.rows =(await  this.sq.query('select count(*) as num '+ sql,{ type: SequelizeClass.QueryTypes.SELECT}))[0].num;
        page.totalPage = Math.ceil(page.rows/pageSize);
        if(pageNumber >= page.totalPage){
            page.lastPage =  true;
        }
        if(pageNumber == 1 || page.totalPage == 1){
            page.firstPage =  true;
        }
        let offset = pageSize * (pageNumber - 1);
        if (offset <=0) offset = 0;
        let sqlToExe = `${selectFields} ${sql} LIMIT ${offset},${pageSize}`;

        page.list = await  this.sq.query(sqlToExe,{ type: SequelizeClass.QueryTypes.SELECT});



        return page;
    }


}